package com.atguigu.tingshu.user.service.impl;

import java.util.Date;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.*;
import com.atguigu.tingshu.user.mapper.*;
import com.atguigu.tingshu.user.strategy.PaidRecordStrategy;
import com.atguigu.tingshu.user.strategy.factory.StrategyFactory;
import com.google.common.collect.Maps;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.cache.GuiGuCache;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.validation.ValidationProviderResolver;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private KafkaService kafkaService;

    /**
     * 微信登录
     *
     * @param code 小程序wx.login()获取调用微信服务端临时票据（有效次数一次，有效时间5分钟）
     * @return {"token":"用户令牌"}
     */
    @Override
    public Map<String, String> wxLogin(String code) {
        try {
            //1.获取当前用户微信账户唯一标识
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            if (sessionInfo != null) {
                String wxOpenId = sessionInfo.getOpenid();
                //2.判断唯一标识是否已关联用户（是否首次登录）
                LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(UserInfo::getWxOpenId, wxOpenId);
                queryWrapper.last("limit 1");
                UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);

                //3.如果是首次登录，注册用户信息（关联微信唯一标识，初始化账户（余额）记录）
                if (userInfo == null) {
                    //3.1 构建用户信息对象，保存用户信息
                    userInfo = new UserInfo();
                    userInfo.setWxOpenId(wxOpenId);
                    userInfo.setNickname("听友" + IdUtil.getSnowflakeNextId());
                    userInfo.setAvatarUrl("https://thirdwx.qlogo.cn/mmopen/vi_32/hFKeRpRQU4wG…axvke5nueicggowdBricR4pspWbp6dwFtLSCWJKyZGJoQ/132");
                    userInfo.setIsVip(0);
                    userInfoMapper.insert(userInfo);
                    //3.2 基于Kakfa异步消息初始化账户余额 新用户注册：赠送10点
                    Map<String, Object> data = new HashMap<>();
                    data.put("userId", userInfo.getId());
                    data.put("title", "新用户注册，赠送礼金");
                    data.put("amount", new BigDecimal("100"));
                    data.put("orderNo", "zs" + IdUtil.getSnowflakeNextId());
                    kafkaService.sendMessage(KafkaConstant.QUEUE_USER_REGISTER, JSON.toJSONString(data));
                }
                //4.为当前用户生成token将用户基本信息UserInfoVo存入Redis
                //4.1 生成唯一token令牌
                String token = IdUtil.randomUUID();

                //4.2 构建登录用户key 前缀：token
                String key = RedisConstant.USER_LOGIN_KEY_PREFIX + token;

                //4.3 将用户信息转为UserInfoVo存入Redis
                UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class);
                redisTemplate.opsForValue().set(key, userInfoVo, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);

                //5.响应token封装到对象中
                Map<String, String> map = new HashMap<>();
                map.put("token", token);
                return map;
            }
        } catch (WxErrorException e) {
            log.error("[用户服务]微信登录异常：{}", e);
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * 获取当前用户基本信息
     *
     * @param userId
     * @return
     */
    @Override
    @GuiGuCache(prefix = "user:info:")
    public UserInfoVo getUserInfo(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Assert.notNull(userInfo, "用户{}信息不存在", userId);
        return BeanUtil.copyProperties(userInfo, UserInfoVo.class);
    }

    /**
     * 更新用户信息
     *
     * @param userId
     * @param userInfoVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(Long userId, UserInfoVo userInfoVo) {
        //只允许修改基本信息
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setNickname(userInfoVo.getNickname());
        userInfo.setAvatarUrl(userInfoVo.getAvatarUrl());
        userInfoMapper.updateById(userInfo);
    }


    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper;

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    /**
     * 检查专辑页中每一页中声音对应购买请求
     *
     * @param userId                    用户ID
     * @param albumId                   专辑ID
     * @param needCheckBuyStatuTrackIds 待检查购买情况声音ID列表（调用前免费试听去掉）
     * @return {声音ID:购买情况}  购买情况：1：已购  0：未购
     */
    @Override
    public Map<Long, Integer> userIsPaidTrack(Long userId, long albumId, List<Long> needCheckBuyStatuTrackIds) {
        Map<Long, Integer> buyState = new HashMap<Long, Integer>();
        //1.判断用户是否已购专辑（说明专辑价格类型整张专辑购买）
        //1.1 根据用户ID+专辑ID查询已购专辑表
        LambdaQueryWrapper<UserPaidAlbum> userPaidAlbumLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getUserId, userId);
        userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getAlbumId, albumId);
        userPaidAlbumLambdaQueryWrapper.last("limit 1");
        Long count = userPaidAlbumMapper.selectCount(userPaidAlbumLambdaQueryWrapper);
        if (count > 0) {
            //1.2 已购买专辑，将提交待检查购买情况声音ID列表购买情况设置为1
            for (Long needCheckBuyStatuTrackId : needCheckBuyStatuTrackIds) {
                buyState.put(needCheckBuyStatuTrackId, 1);
            }
            return buyState;
        }

        //2.判断用户是否购买过声音
        //2.1 根据用户ID+专辑ID查询已购声音表得到已购声音集合
        LambdaQueryWrapper<UserPaidTrack> userPaidTrackLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userPaidTrackLambdaQueryWrapper.eq(UserPaidTrack::getUserId, userId);
        userPaidTrackLambdaQueryWrapper.eq(UserPaidTrack::getAlbumId, albumId);
        userPaidTrackLambdaQueryWrapper.select(UserPaidTrack::getTrackId);
        List<UserPaidTrack> userPaidTrackList = userPaidTrackMapper.selectList(userPaidTrackLambdaQueryWrapper);
        //2.2 如果不存在已购声音,将提交待检查购买情况声音ID列表购买情况设置为0
        if (CollectionUtil.isEmpty(userPaidTrackList)) {
            for (Long needCheckBuyStatuTrackId : needCheckBuyStatuTrackIds) {
                buyState.put(needCheckBuyStatuTrackId, 0);
            }
            return buyState;
        }
        //2.3 如果存在已购声音，判断将已购声音购买情况设置为：1 未购买设置为：0
        List<Long> userPaidTrackIdList = userPaidTrackList.stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
        for (Long needCheckBuyStatuTrackId : needCheckBuyStatuTrackIds) {
            if (userPaidTrackIdList.contains(needCheckBuyStatuTrackId)) {
                //说明已购买该声音
                buyState.put(needCheckBuyStatuTrackId, 1);
            } else {
                //说明未购买该声音
                buyState.put(needCheckBuyStatuTrackId, 0);
            }
        }
        return buyState;
    }

    /**
     * 判断当前用户是否购买指定专辑
     *
     * @param userId
     * @param albumId
     * @return
     */
    @Override
    public Boolean isPaidAlbum(Long userId, Long albumId) {
        LambdaQueryWrapper<UserPaidAlbum> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPaidAlbum::getAlbumId, albumId);
        queryWrapper.eq(UserPaidAlbum::getUserId, userId);
        Long count = userPaidAlbumMapper.selectCount(queryWrapper);
        return count > 0;
    }

    /**
     * 查询用户某个专辑已购声音ID列表
     *
     * @param userId
     * @param albumId
     * @return
     */
    @Override
    public List<Long> getUserPaidTrackIdList(Long userId, Long albumId) {
        LambdaQueryWrapper<UserPaidTrack> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPaidTrack::getUserId, userId);
        queryWrapper.eq(UserPaidTrack::getAlbumId, albumId);
        queryWrapper.select(UserPaidTrack::getTrackId);
        List<UserPaidTrack> userPaidTrackList = userPaidTrackMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(userPaidTrackList)) {
            List<Long> userPaidTrackIdList = userPaidTrackList.stream().map(UserPaidTrack::getTrackId)
                    .collect(Collectors.toList());
            return userPaidTrackIdList;
        }
        return null;
    }


    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Autowired
    private UserVipServiceMapper userVipServiceMapper;

    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;


    @Autowired
    private StrategyFactory strategyFactory;

    /**
     * 虚拟物品发货，新增用户购买记录-处理购买类型：1.专辑 2.声音 3.会员
     *
     * @param userPaidRecordVo 购买记录VO对象 项目类型: 1001-专辑 1002-声音 1003-vip会员
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        PaidRecordStrategy strategy = strategyFactory.getStrategyByItemType(userPaidRecordVo.getItemType());
        strategy.handlerPaidRecord(userPaidRecordVo);
       /* //1.处理购买项目类型为专辑
        if (SystemConstant.ORDER_ITEM_TYPE_ALBUM.equals(userPaidRecordVo.getItemType())) {
            //1.1 根据入参订单编号查询购买是否存在
            LambdaQueryWrapper<UserPaidAlbum> paidAlbumLambdaQueryWrapper = new LambdaQueryWrapper<>();
            paidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getOrderNo, userPaidRecordVo.getOrderNo());
            Long count = userPaidAlbumMapper.selectCount(paidAlbumLambdaQueryWrapper);
            if (count == 0) {
                //1.2 不存在则新增购买记录，反之说明已处理忽略即可
                UserPaidAlbum userPaidAlbum = new UserPaidAlbum();
                userPaidAlbum.setOrderNo(userPaidRecordVo.getOrderNo());
                userPaidAlbum.setUserId(userPaidRecordVo.getUserId());
                userPaidAlbum.setAlbumId(userPaidRecordVo.getItemIdList().get(0));
                userPaidAlbumMapper.insert(userPaidAlbum);
            }
        } else if (SystemConstant.ORDER_ITEM_TYPE_TRACK.equals(userPaidRecordVo.getItemType())) {
            //2.处理购买项目类型为声音
            LambdaQueryWrapper<UserPaidTrack> paidTrackLambdaQueryWrapper = new LambdaQueryWrapper<>();
            paidTrackLambdaQueryWrapper.eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo());
            Long count = userPaidTrackMapper.selectCount(paidTrackLambdaQueryWrapper);
            if (count == 0) {
                //1.2 不存在则新增购买记录，反之说明已处理忽略即可
                TrackInfo trackInfo = albumFeignClient.getTrackInfo(userPaidRecordVo.getItemIdList().get(0)).getData();
                for (Long paidTrackId : userPaidRecordVo.getItemIdList()) {
                    UserPaidTrack userPaidTrack = new UserPaidTrack();
                    userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
                    userPaidTrack.setUserId(userPaidRecordVo.getUserId());
                    userPaidTrack.setAlbumId(trackInfo.getAlbumId());
                    userPaidTrack.setTrackId(paidTrackId);
                    userPaidTrackMapper.insert(userPaidTrack);
                }
            }
        } else if (SystemConstant.ORDER_ITEM_TYPE_VIP.equals(userPaidRecordVo.getItemType())) {
            //3.处理购买项目类型为VIP会员
            //3.1 根据入参订单编号查询购买是否存在
            LambdaQueryWrapper<UserVipService> vipServiceLambdaQueryWrapper = new LambdaQueryWrapper<>();
            vipServiceLambdaQueryWrapper.eq(UserVipService::getOrderNo, userPaidRecordVo.getOrderNo());
            Long count = userVipServiceMapper.selectCount(vipServiceLambdaQueryWrapper);
            if (count == 0) {
                //3.1 保存本次会员购买记录
                UserVipService userVipService = new UserVipService();
                userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
                userVipService.setUserId(userPaidRecordVo.getUserId());
                //3.1.1 根据用户ID查询用户信息 判断当前用户是否为VIP
                UserInfoVo userInfo = this.getUserInfo(userPaidRecordVo.getUserId());
                Boolean isVIP = false;
                if (userInfo.getIsVip().intValue() == 1 && userInfo.getVipExpireTime().after(new Date())) {
                    isVIP = true;
                }
                //3.1.2 如果是普通用户 本次会员起始时间=当前时间 过期时间：当前时间+会员服务月数
                //3.2 查询套餐信息
                VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(userPaidRecordVo.getItemIdList().get(0));
                if (!isVIP) {
                    //普通用户 新开会员
                    userVipService.setStartTime(new Date());
                    DateTime expireDate = DateUtil.offsetMonth(new Date(), vipServiceConfig.getServiceMonth());
                    userVipService.setExpireTime(expireDate);
                } else {
                    //3.1.3 如果是VIP-续期会员 本次会员起始时间=当前会员过期时间 过期时间：当前会员过期时间+会员服务月数
                    DateTime startTime = DateUtil.offsetDay(userInfo.getVipExpireTime(), 1);
                    userVipService.setStartTime(startTime);
                    userVipService.setExpireTime(DateUtil.offsetMonth(startTime, vipServiceConfig.getServiceMonth()));
                }
                userVipServiceMapper.insert(userVipService);
                //3.2 用户表会员过期时间
                userInfo.setIsVip(1);
                userInfo.setVipExpireTime(userVipService.getExpireTime());
                userInfoMapper.updateById(BeanUtil.copyProperties(userInfo, UserInfo.class));
            }
        }*/

    }

    /**
     * 更新会员标识
     */
    @Override
    public void updateVipExpireStatus() {
        //1.根据VIP=1 且 VIP过期时间小于当前时间
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getIsVip, 1);
        queryWrapper.lt(UserInfo::getVipExpireTime, new Date());
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);

        //2.更新会员标识
        if(CollectionUtil.isNotEmpty(userInfoList)){
            for (UserInfo userInfo : userInfoList) {
                userInfo.setIsVip(0);
                userInfoMapper.updateById(userInfo);
            }
        }
    }
}
